<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { queryNews } from '@/api/index'

const { safeAreaInsets } = uni.getSystemInfoSync()

// 快捷功能数据
const quickLinks = [
  { icon: '/static/tabs/考研书籍.png', text: '考研笔记', url: '/pages/notes/notes' },
  { icon: '/static/tabs/考研倒计时.png', text: '备考日历', url: '/pages/calendar/calendar' },
  { icon: '/static/tabs/考研大纲.png', text: '资料下载', url: '/pages/download/download' },
  { icon: '/static/tabs/考研报名.png', text: '收藏', url: '/pages/community/community' },
]

// 新闻数据
const newsList = ref([])

// 获取新闻列表
const getNewsList = async () => {
  try {
    uni.showLoading({ title: '加载中...' })
    const res = await queryNews()

    if (res.statusCode === 200 && res.data) {
      const responseData = res.data

      if (responseData.code === 200) {
        newsList.value = responseData.data
      }
    }
  } catch (error) {
    console.error('获取新闻列表失败', error)
  } finally {
    uni.hideLoading()
  }
}

// 打开新闻链接
const openNewsLink = (link) => {
  if (!link) {
    console.error('链接为空')
    uni.showToast({
      title: '链接无效',
      icon: 'none',
    })
    return
  }

  try {
    console.log('准备打开链接:', link)
    // 使用webview页面打开链接
    const url = `/pages/webview/webview?url=${encodeURIComponent(link)}`
    console.log('跳转webview页面:', url)

    uni.navigateTo({
      url: url,
      success: () => {
        console.log('跳转成功')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        // 失败时尝试使用系统浏览器打开
        uni.showModal({
          title: '提示',
          content: '是否使用浏览器打开链接?',
          success: (res) => {
            if (res.confirm) {
              // #ifdef H5
              window.open(link)
              // #endif

              // #ifdef APP-PLUS
              plus.runtime.openURL(link)
              // #endif

              // #ifdef MP
              uni.setClipboardData({
                data: link,
                success: () => {
                  uni.showToast({
                    title: '链接已复制，请在浏览器中打开',
                    icon: 'none',
                  })
                },
              })
              // #endif
            }
          },
        })
      },
    })
  } catch (e) {
    console.error('处理链接时出错:', e)
  }
}

// 导航到相应页面
const navigateToPage = (url) => {
  uni.navigateTo({
    url,
    fail: (err) => {
      console.error('页面跳转失败', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none',
      })
    },
  })
}

// 格式化日期显示
const formatDate = (dateStr) => {
  if (!dateStr) return ''

  // 检查是否已经是格式化的字符串
  if (typeof dateStr === 'string' && dateStr.includes('-')) {
    return dateStr
  }

  try {
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return dateStr

    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
      date.getDate(),
    ).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(
      date.getMinutes(),
    ).padStart(2, '0')}`
  } catch (e) {
    console.error('日期格式化错误:', e)
    return dateStr
  }
}

// 页面加载时获取新闻列表
onMounted(() => {
  getNewsList()
})
</script>

<template>
  <view class="index-container">
    <view class="header">
      <!-- 状态栏占位 -->
      <view class="status-bar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
        <view class="logo">
          <image class="logo-image" src="@/static/images/考研.png" mode="aspectFit"></image>
          <text class="logo-text">梅花 香自苦寒来</text>
        </view>
      </view>

      <!-- 搜索框 -->
      <view class="search-box">
        <view class="search-input">
          <text class="uni-icon-search"></text>
          <text class="placeholder">搜索考研资讯、学校、专业</text>
        </view>
      </view>
    </view>

    <!-- 快捷功能区 -->
    <view class="quick-links">
      <view
        class="quick-link"
        v-for="item in quickLinks"
        :key="item.text"
        @tap="navigateToPage(item.url)"
      >
        <image :src="item.icon" mode="aspectFit" class="quick-icon"></image>
        <text class="quick-text">{{ item.text }}</text>
      </view>
    </view>

    <!-- 热门资讯 -->
    <view class="section hot-news">
      <view class="section-header">
        <text class="section-title">热门资讯</text>
        <text class="more">更多 ></text>
      </view>
      <view class="news-list">
        <XtxSwiper></XtxSwiper>
      </view>
    </view>

    <!-- 学校公告 -->
    <view class="section announcements">
      <view class="section-header">
        <text class="section-title">学校公告</text>
        <text class="more" @tap="getNewsList">更多 ></text>
      </view>
      <view class="announcement-list">
        <view v-if="newsList.length === 0" class="empty-data">
          <text>暂无公告</text>
        </view>
        <view
          class="announcement-item"
          v-for="item in newsList"
          :key="item.id"
          @tap="openNewsLink(item.link)"
        >
          <view class="announcement-content">
            <text class="announcement-title">{{ item.title }}</text>
            <view class="announcement-info">
              <text class="announcement-source">来源: {{ item.source }}</text>
              <text class="announcement-date">{{
                formatDate(
                  item.createdTime || item.createTime || item.updateTime || item.updatedTime || '',
                )
              }}</text>
            </view>
          </view>
          <text class="uni-icon-forward"></text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';

.index-container {
  min-height: 100vh;
  background-color: #f8f8f8;

  .header {
    height: 400rpx;
    background: linear-gradient(180deg, $theme-color 0%, $light-theme-color 100%);
    border-radius: 0 0 40rpx 40rpx;
    padding: 0 30rpx;

    .status-bar {
      .logo {
        display: flex;
        align-items: center;
        height: 88rpx;

        .logo-image {
          width: 60rpx;
          height: 60rpx;
        }

        .logo-text {
          color: #fff;
          font-size: 32rpx;
          margin-left: 16rpx;
          font-weight: bold;
        }
      }
    }

    .search-box {
      margin-top: 20rpx;

      .search-input {
        height: 72rpx;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 36rpx;
        display: flex;
        align-items: center;
        padding: 0 30rpx;

        .uni-icon-search {
          font-size: 36rpx;
          color: #666;
        }

        .placeholder {
          color: #999;
          font-size: 28rpx;
          margin-left: 10rpx;
        }
      }
    }
  }

  .quick-links {
    margin: -80rpx 30rpx 0;
    padding: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    display: flex;
    justify-content: space-between;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .quick-link {
      display: flex;
      flex-direction: column;
      align-items: center;

      .quick-icon {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 16rpx;
      }

      .quick-text {
        font-size: 24rpx;
        color: #333;
      }
    }
  }

  .section {
    margin: 30rpx;
    background: #fff;
    border-radius: 20rpx;
    padding: 30rpx;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;

      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .more {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .announcements {
    .announcement-list {
      .announcement-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        margin-bottom: 20rpx;
        background-color: #fff;
        border-radius: 16rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
        border-left: 6rpx solid $theme-color;

        &:last-child {
          margin-bottom: 0;
        }

        .announcement-content {
          flex: 1;
          margin-right: 20rpx;

          .announcement-title {
            font-size: 28rpx;
            color: #333;
            line-height: 1.5;
            font-weight: 500;
          }

          .announcement-info {
            display: flex;
            flex-direction: column;
            margin-top: 10rpx;

            .announcement-source {
              font-size: 24rpx;
              color: #666;
            }

            .announcement-date {
              font-size: 22rpx;
              color: #999;
              margin-top: 5rpx;
            }
          }
        }

        .uni-icon-forward {
          color: #ccc;
          font-size: 24rpx;
          padding: 10rpx;
        }
      }

      .empty-data {
        text-align: center;
        padding: 40rpx 0;
        color: #999;
      }
    }
  }
}
</style>
